class Store {
  constructor() {
    this.store = {};
    this.subscribers = new Map();
    this.dispatch = (key, value) => {
      this.store[key] = value;
    };
    Object.freeze(this.store);
    Object.freeze(this.subscribers);
  }
  setDefault(val) {
    this.store = this.reactive(val);
  }
  reactive(val) {
    const _this = this;
    return new Proxy(val, {
      get: function (target, key) {
        if (
          Object.prototype.toString.call(target[key]) === "[object Function]"
        ) {
          // 发送通知，更新所有组件中对应key的值
          _this.depend(key, target[key]);
        }
        return target[key];
      },
      set: function (target, key, value) {
        let result = Reflect.set(target, key, value);
        // 发送通知，更新所有组件中对应key的值
        _this.depend(key, value);
        return result;
      },
    });
  }
  depend(key, value) {
    this.notice(key, value);
  }
  notice(key, value) {
    if (this.subscribers.has(key)) {
      for (let callback of this.subscribers.get(key)) {
        callback(value);
      }
    }
  }
  subscribe(key, callback) {
    if (!this.subscribers.has(key)) {
      this.subscribers.set(key, new Set());
    }
    this.subscribers.get(key).add(callback);
  }
  unsubscribe(key, callback) {
    const subscribersSet = this.subscribers.get(key);
    if (subscribersSet) {
      subscribersSet.delete(callback);
      if (subscribersSet.size === 0) {
        this.subscribers.delete(key);
      }
    }
  }
}
module.exports = Store;
